<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Workerman\Worker;
use Workerman\Mqtt\Client;
use App\Models\HardWareApi\TrashMessage;
use Grimzy\LaravelMysqlSpatial\Types\Point;

class MqttManageCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mqtt {action} {--d}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Start a Mqtt server.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        global $argv;
        $arg = $this->argument('action');
        $argv[1] = $argv[2];
        $argv[2] = isset($argv[3]) ? "-{$argv[3]}" : '';

        $this->start();
    }

    private function start()
    {
        $this->subscribeManage();
        Worker::runAll();
    }

    //订阅主题消息
    public function subscribeManage()
    {
        $worker = new Worker();
        $worker->onWorkerStart = function(){
            $userInfo = [
                'username' => 'kpphbem/xiaotu',
                'password' => '0J87u5FSzdmRsLSz',
            ];
            $mqtt = new Client('mqtt://kpphbem.mqtt.iot.gz.baidubce.com:1883', $userInfo);
            $mqtt->onConnect = function($mqtt) {

                echo "connect mqtt success!\r\n";
                //订阅消息主题
                $topic = 'xiaotu/receiveMessage/trash/+';
                $mqtt->subscribe($topic, null, function(){
                    echo "topic subscribe success!\r\n";
                });

                //订阅消息逻辑处理
                $mqtt->onMessage = function($topic, $message, $mqtt){
                    echo $message."\r\n";
                    //1、查询主题是否在垃圾桶数据表中
                    $imei =  substr($topic,strrpos($topic,"/")+1);
                    $TrashData = TrashMessage::where('imei',$imei)->get();
                    //设备更新
                    $message = json_decode($message,true);
                    if($TrashData != []){
                        if($message['cmd'] == 4){
                            $data = $message['dev_sta'];
                            //重新拼接经纬度
                            $location = $data['lon'] . " " . $data['lat'];
                            $data['location'] = Point::fromString($location);
                            unset($data['lon']);//注销经度
                            unset($data['lat']);//注销纬度
                            $data['ir_sta'] = implode(",", $data['ir_sta']);
                            //更新数据
                            $res = TrashMessage::where('imei',$imei)->update($data);
                            //应答消息主题
                            $responseTopic = 'xiaotu/postMessage/trash/'.$imei;
                            $responseInfo = '';
                            if($res){
                                //更新成功
                                $responseInfo = '{"imei":"'.$imei.'","ts": '. time() .',"cmd":4}';
                            }else{
                                //更新失败--重新发送数据
                                $responseInfo = '{"imei":"'.$imei.'","ts": '. time() .',"cmd":1}';
                            }
                            $mqtt->publish($responseTopic,$responseInfo);
                        }
                    }
                };

                //模拟垃圾桶数据发送
                // $message = '{"imei":"863700381024867","ts": '. time() .',"cmd":4,"dev_sta": {"gps_sta":1, "lon":"104.06315","lat": "30.56863","lac":34860,"ci":62041,"ir_sta":[0,0,1],"distance":"0.55","power_vol":"3.122"}}';
                // $mqtt->publish('xiaotu/receiveMessage/trash/863700381024867', $message);
            };
            $mqtt->connect();
        };
    }
}
